<template>
	<view>
		<u-navbar title="批量上传" :is-back="true" :title-size="30" :border-bottom="false"></u-navbar>
		<view class="tips">
			批量上传xlsx时，<br />
			<text style="color: red;">当月日期数请认真确认是否正确,所填班表是否正确</text><br />
			<text style="color: red;">批量上传当月班表不会修改已经过的日期，只会修改当天后面的日期</text>
			<text>，次月上传，直接覆盖之前次月的班表</text>
			<!-- <span></span><br /> -->
		</view>
		<view class="demonstration">
			<view class="fileWrap">
				<view ref="fileView" class="hFile">
					<!-- 自定义上传组件样式 -->
					<slot name="upload" class="upload">

						<view class="upload-bg" @click="chooseFile">
							<uni-icons type="cloud-upload" size="36"></uni-icons>
							<text>{{uploadText}}</text>
						</view>
					</slot>
				</view>
			</view>
		</view>

		<view style="margin: 0 20upx;">
			<u-form ref="uForm">
				<u-form-item label="点击选择上传年月时间" prop="time" label-width="360"
					:label-style="{ fontSize: '16px', color: 'red' }">
					<u-input type="text" v-model="yearMonth" placeholder="关键词" clearable @click="pickerShow = true"
						:disabled="true" />
				</u-form-item>
			</u-form>

		</view>

		<uni-table :loading="loading" ref="table" border stripe emptyText="暂无更多数据">
			<uni-tr>
				<uni-th align="center" v-for="(item,index) in tableTitles" :key="index" width="150px">{{item}}</uni-th>
			</uni-tr>
			<uni-tr v-for="(item,index) in tableList" :key="index">
				<uni-td align="center" v-for="(items,i) in item" :key="i">
					<input :value="items" type="text" :class="{'disabled': isDisabled(i)}"
						@input="handleInputChange(index, i, $event)" />
				</uni-td>
			</uni-tr>
		</uni-table>
		<!-- <jonej-xlsxAnalysis ref="xlsxAnalysis" @scheduleList="handleScheduleList"></jonej-xlsxAnalysis> -->
		<!--  this.$refs.xlsxAnalysis && this.$refs.xlsxAnalysis.tableList && this.$refs.xlsxAnalysis.tableList.length < 2 -->
		<!-- :class="{ 'nextNone': !loading}" -->
		<view class="addSite " @tap="toUpload" >
			<view class="add">
				上传
			</view>
		</view>

		<u-picker mode="time" v-model="pickerShow" :params="params" @confirm="handlepicker"></u-picker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				uploadText: '上传xlsx文件',
				batchClass: [],

				yearMonth: new Date().toISOString().slice(0, 7),
				pickerShow: false,
				params: {
					year: true,
					month: true,
					day: false,
					hour: false,
					minute: false,
					second: false
				},
				currentMonth: 0,
				week: [],
				date: [],
				month: String(new Date().getMonth() + 1).padStart(2, '0'),
				newYear: '',
				newMonth: '',
				loading: false,
				tableTitles: [],
				tableList: [],
			}
		},
		onLoad(options) {
			// 检查 options 和 options.data 的有效性
			if (options && typeof options.data === 'string' && options.data.trim()) {
				try {
					const data = JSON.parse(options.data);
					// 检查 data.year 和 data.month 是否存在
					if (data.year && data.month) {
						this.yearMonth = `${data.year}-${data.month}`;
						this.newYear = data.year
						this.newMonth = data.month
						this.month = data.month
						this.$refs.xlsxAnalysis.month = Number(data.month)
					}
				} catch (error) {
					console.error("JSON解析错误:", error);
				}
			}
			// const data = JSON.parse(options.data)
			// this.yearMonth = `${data.year}-${data.month}`

			this.$u.vuex('vuex_url', '/pages/batchschedule/batchschedule');
			this.getMonthCalendar(this.newYear, this.newMonth)
			this.loading = this.$refs.xlsxAnalysis.loading
			console.log("获取", this.loading);
		},
		methods: {
			isDisabled(index) {

				return index > 3 && index - 3 <= new Date().getDate() && new Date().getMonth() + 1 == this.month;
			},
			getMonthCalendar(year, month) {
				// 创建一个存储星期几的数组
				const weekdays = ['日', '一', '二', '三', '四', '五', '六']

				// 初始化结果数组
				const date = []
				const week = []

				if (year == undefined || year == '' || month == undefined || month == '') {
					year = new Date().getFullYear()
					month = new Date().getMonth() + 1
				}
				// 添加每一天的日期和星期
				const daysInMonth = new Date(year, month, 0).getDate()
				this.date = ["姓名", "工号", "专柜", "日期"]
				this.week = ["", "", "", "星期"]
				for (let i = 1; i <= daysInMonth; i++) {
					const weekday = weekdays[(new Date(year, month - 1, i).getDay())]
					this.date.push(i)
					this.week.push(weekday)
				}
			},

			getList() {
				const {
					merchantName
				} = this.vuex_qy;
				const yearMonth = this.yearMonth.replace(/-/g, '');
				const data = {
					merchantName,
					yearMonth
				};
				return this.$u.api.Entrydeparture.list(data);
			},
			handlepicker(e) {

				// this.form.year = e.year
				this.yearMonth = e.year + "-" + e.month
				this.month = e.month
				this.$refs.xlsxAnalysis.month = Number(e.month)
				this.$refs.xlsxAnalysis.tableList = []
				this.getMonthCalendar(e.year, e.month)
				// const rawData = await this.getList()
				// this.$refs.xlsxAnalysis.tableTitles = this.date
				// this.$refs.xlsxAnalysis.tableList = this.reverseJsonObject(rawData.list)
				// console.log(this.$refs.xlsxAnalysis.tableList);
			},
			toUpload() {
				this.$u.debounce(() => {
						const data = {
							yearMonth: this.yearMonth.replace(/-/g, ''),
							list: this.batchClass
						}
						
						this.$u.api.Entrydeparture.batch(data).then(res => {
							uni.showToast({
								title: '班表上传成功',
								icon: 'none',
								duration: 2000 // 持续时间为 2 秒
							});
							this.batchClass = []
							this.$refs.xlsxAnalysis.tableList = []
							uni.redirectTo({
								url: '/pages/schedule/schedule'
							})
						})
					}
					, 1000)
			},

			convertToClassifyString(classify) {
				return classify.map(item => {
					return `${item.label}:${item.value}`;
				});
			},


			// 获取指定格式
			createJsonObject(dataArray) {
				
				return dataArray.map(data => {
					const [name, jobNo, merchantName, ...classify] = data;

					return {
						name,
						jobNo,
						merchantName,
						classify: this.convertToLabelValueArray(classify)
					};
				});
			},

			convertToLabelValueArray(inputArray) {
				const resultArray = inputArray
					.filter(item => item.trim() !== '') // 过滤掉空字符串元素
					.map((value, index) => ({
						label: index + 1,
						value
					}));

				return JSON.stringify(resultArray);
			},
			// 获取exls数据
			// async handleScheduleList(scheduleList) {

			// 	// const remainingData = scheduleList.slice(1);
			// 	// this.batchClass = this.createJsonObject(remainingData)
			// 	this.batchClass = this.createJsonObject(scheduleList)

			// 	const rawData = await this.getList()
			// 	const today = new Date().getDate()
			// 	const month = String(new Date().getMonth() + 1).padStart(2, '0')

			// 	this.batchClass.forEach(item => {
			// 		const itemClassify = JSON.parse(item.classify);

			// 		itemClassify.forEach(i => {
			// 			if (i.label <= today) {
			// 				rawData.list.forEach(bItem => {
			// 					if (bItem.jobNo === item.jobNo) {
			// 						const batchItemClassify = JSON.parse(bItem.classify);
			// 						const matchingBatchItemData = batchItemClassify.find(
			// 							bData => bData.label === i.label);
			// 						if (matchingBatchItemData) {
			// 							i.value = matchingBatchItemData.value;
			// 						}
			// 					}
			// 				});
			// 			}
			// 		});

			// 		if (this.month === month) {
			// 			item.classify = JSON.stringify(itemClassify);
			// 		}

			// 	});
			// 	this.$refs.xlsxAnalysis.tableTitles = this.date
			// 	this.$refs.xlsxAnalysis.tableList = [this.week, ...this.reverseJsonObject(this.batchClass)];
			// 	// 等待 DOM 更新完成后执行的方法
			// 	this.$nextTick(() => {
			// 		this.$refs.xlsxAnalysis.loading = false 
			// 		this.loading = true
			// 	});

			// 	// console.log("获取当前状态",this.$refs.xlsxAnalysis.loading);
			// 	// console.log("状态",this.loading);
			// 	// console.log("shuju1",this.$refs.xlsxAnalysis.tableList);
			// },
			async handleScheduleList(scheduleList) {
				this.batchClass = this.createJsonObject(scheduleList);
				
				console.log(this.batchClass);
				const rawData = await this.getList();
				const today = new Date().getDate();
				const month = String(new Date().getMonth() + 1).padStart(2, '0');
				
				this.batchClass.forEach(item => {
					const itemClassify = JSON.parse(item.classify);

					itemClassify.forEach(i => {
						if (i.label <= today) {
							const matchingBatchItem = rawData.list.find(bItem =>
								bItem.jobNo === item.jobNo &&
								JSON.parse(bItem.classify).some(bData => bData.label === i.label)
							);

							if (matchingBatchItem) {
								const batchItemClassify = JSON.parse(matchingBatchItem.classify);
								const matchingBatchItemData = batchItemClassify.find(bData => bData
									.label === i.label);
								if (matchingBatchItemData) {
									i.value = matchingBatchItemData.value;
								}
							}
						}
					});

					if (this.month === month) {
						item.classify = JSON.stringify(itemClassify);
					}
				});

				this.$refs.xlsxAnalysis.tableTitles = this.date;
				this.$refs.xlsxAnalysis.tableList = [this.week, ...this.reverseJsonObject(this.batchClass)];
				
				// 等待 DOM 更新完成后执行的方法
				await this.$nextTick();
				this.$refs.xlsxAnalysis.loading = false;
				this.loading = true;
				uni.hideLoading()
			},

			reverseJsonObject(dataArray) {
				return dataArray.map(data => {
					const {
						name,
						jobNo,
						merchantName,
						classify
					} = data;
					const classifyArray = this.reverseConvertToClassifyString(JSON.parse(classify));
					return [name, jobNo, merchantName, '', ...classifyArray];
				});
			},

			reverseConvertToClassifyString(classify) {
				return classify.map(item => {
					return item.value;
				});
			},

			// 选择文件上传
			chooseFile() {
				

				// const that = this
				// that.loading = that.$refs.xlsxAnalysis.loading
				// wx.qy.checkSession({
				// 	success: function(res) {
				// 		that.$refs.xlsxAnalysis.chooseFile()
				// 		//session_key 未过期，并且在本生命周期一直有效
				// 	},
				// 	fail: function(err) {
				// 		// session_key 已经失效，需要重新执行登录流程
				// 		// wx.qy.login() //重新登录
				// 		console.log("失败返回", err);
				// 		that.$u.route({
				// 			type: 'reLaunch',
				// 			url: '/pages/login/login'
				// 		})
				// 	}
				// })
				
				
				const that = this; // 保存当前上下文
				uni.chooseMessageFile({
					count: 1, // 选择的文件数量
					type: 'file', // 文件类型
					extension: ['.xlsx', '.xls'], // 允许的文件扩展名
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFiles; // 获取选择的文件信息

						that.tableList = []
						that.tableTitles = []
						// uni.uploadFile({
						// 	url: url, // 上传的接口地址
						// 	filePath: tempFilePaths[0], // 选择的文件路径
						// 	name: 'file', // 上传的字段名
						// 	header: {
						// 		'guideToken': that.vuex_qy_token // 添加请求头中的token
						// 	},
						// 	success: (uploadFileRes) => {
						// 		console.log(uploadFileRes.data); // 打印上传结果
						// 	}
						// });
						this.uploadFile(tempFilePaths)


					}
				});

			},
			async uploadFile(tempFilePaths) {
				const url = this.domain + '/api/v3/guide/schedule/xlsxUpload'; // 构建上传URL
				const that = this
				
				await uni.uploadFile({
					url: url, // 上传的接口地址
					filePath: tempFilePaths[0].path, // 选择的文件路径
					name: 'file', // 上传的字段名
					formData: {
						year: that.yearMonth.substring(0, 4),
						month: that.yearMonth.substring(5,7)
					},
					header: {
						'guideToken': that.vuex_qy_token // 添加请求头中的token
					},
					success(uploadFileRes) {
						const res = JSON.parse(uploadFileRes.data)
						if(res.data !== null){
							that.tableTitles = res.data.header;
							// that.tableList = res.data.list
							that.text(res.data.list.slice(1))
							
							
							
							
						}else{
							// uni.showToast({
							// 	title: res.msg,
							// 	icon: 'none',
							// 	duration: 2000
							// });
							wx.showModal({
								title: '提示',
								content: res.msg,
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						}
						// that.tableTitles = res.data.header;
						// that.tableList = res.data.list
						// this.$refs.xlsxAnalysis.tableList = [this.week, ...this.reverseJsonObject(this.batchClass)];
					}
				});
			},
			async text(batchClass){
				
				this.batchClass = this.createJsonObject(batchClass);
				const rawData = await this.getList();
				const today = new Date().getDate();
				const month = String(new Date().getMonth() + 1).padStart(2, '0');
				
				this.batchClass.forEach(item => {
					const itemClassify = JSON.parse(item.classify);
				
					itemClassify.forEach(i => {
						if (i.label <= today) {
							const matchingBatchItem = rawData.list.find(bItem =>
								bItem.jobNo === item.jobNo &&
								JSON.parse(bItem.classify).some(bData => bData.label === i.label)
							);
				
							if (matchingBatchItem) {
								const batchItemClassify = JSON.parse(matchingBatchItem.classify);
								const matchingBatchItemData = batchItemClassify.find(bData => bData
									.label === i.label);
								if (matchingBatchItemData) {
									i.value = matchingBatchItemData.value;
								}
							}
						}
					});
				
					if (this.month === month) {
						item.classify = JSON.stringify(itemClassify);
					}
				});
				this.tableList = this.reverseJsonObject(this.batchClass)
				
			},
		}
	}
</script>

<style lang="scss">
	page {
		padding-bottom: 140upx;
	}

	.demonstration {
		width: 90%;
		margin: 50upx auto;
		background-color: #FAFAFA;
		text-align: center;
		padding: 20upx 0;
		line-height: 100upx;

		.hFile {
			display: flex;
			justify-content: center;
		}

		.upload-bg {
			background-color: rgba(38, 82, 228, 0.07);
			width: 260rpx;
			height: 260rpx;
			display: flex;
			flex-direction: column;
			justify-content: center !important;
			align-items: center !important;
		}
	}

	.addSite {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		padding: 20upx 0;
		padding-bottom: 40upx;
		background-color: #f5f5f5;
		z-index: 99;

		.add {
			text-align: center;
			background-color: #484E5E;
			color: #fff;
			border-radius: 8rpx;
			padding: 20upx 0;
			margin: 0 30upx;
		}
	}

	.tips {
		margin: 20upx 20upx;
		font-size: 35upx;
		font-weight: bold;
	}


	.nextNone {
		pointer-events: none;
		opacity: 0.5;
	}
</style>